<?php

namespace app\api\controller;

use fast\Random;
use think\facade\Validate;
use think\facade\Config;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\controller\Api;
use fast\Http;
use think\facade\Queue;
/**
 * 会员接口.
 */
class User extends Api
{
    
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile','changebankcark','third'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
    }

    /**
     * 会员中心.
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录.
     *
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->request('account');
        $password = $this->request->request('password');
        if (! $account || ! $password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }


    public  function editusertype(){
        $type = $this->request->request("type");
        if(!in_array($type,["0","1","2"])){
            $this->error("类型不对");
        }
        $user = $this->auth->getUser();
        $user->user_type = $type;
        $user->save();
        $this->success("修改成功",["user"=>$user]);
    }

    /**
     * 手机验证码登录.
     *
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        $openid = $this->request->request('openid');
        if (! $mobile || ! $captcha||!$openid) {
            $this->error(__('Invalid parameters'));
        }
        if (! Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (! Sms::check($mobile, $captcha, 'login')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::where('mobile',$mobile)->find();
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $this->error(__('Account is locked'));
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
            $wechat_user = \app\admin\model\WechatUser::where('openid',$openid)->find();
            $user_info = $this->auth->getUser();
            $wechat_user->user_id = $user_info["id"];
            $wechat_user->save();
        }
        if ($ret) {
            Sms::flush($mobile, 'login');
            $user = $this->auth->getUser();
            unset($user->password);
            unset($user->salt);
            $data = ['userinfo' =>$user,"token"=>$this->auth->getToken() ];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员.
     *
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code   验证码
     */
    public function register()
    {
        $username = '默认名称';
        $password = 'Mm123456';
        $email = $this->request->request('mobile').'@163.com';
        $birthday = $this->request->request('birthday');
        $mobile = $this->request->request('mobile');
        $rec_phone = $this->request->request('rec_phone');
        $openid = $this->request->request('openid');
        $code = $this->request->request('code');
        if (! $username || ! $password||!$openid||!$mobile) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && ! Validate::is($email, 'email')) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && ! Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $user = \app\common\model\User::where('mobile',$rec_phone)->find();
        if(!$user){
            $this->error('请填写正确的推荐人');
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        // if (empty($email)) {
        //     $email = $username;
        // }
        // if (empty($mobile)) {
        //     $mobile = $username;
        // }
        
        $wechat_user = \app\admin\model\WechatUser::where('openid',$openid)->find();
        $list['nickname']=$wechat_user->nickname;
        $list['avatar']=$wechat_user->headimgurl;
        $list['rec_user_id']=$user->id;
        $list['is_rec_bind']=1;
        $list['user_type']='1';
        $list['birthday']= $birthday ;
        $ret = $this->auth->register($username, $password, $email, $mobile, $list);
        if ($ret) {
            $wechat_user = \app\admin\model\WechatUser::where('openid',$openid)->find();
            $user_info = $this->auth->getUser();
            $wechat_user->user_id = $user_info["id"];
            $wechat_user->save();
            $data = ['userinfo' => $user_info];
             // echo phpinfo();exit();
        // 1.当前任务由哪个类来负责处理
        // 当轮到该任务时，系统将生成该类的实例，并调用其fire方法
        $FxLoginJobClassName = 'app\job\FxLoginJob';
        $IyunLoginJobClassName = 'app\job\IyunLoginJob';
        // 2.当任务归属的队列名称，如果为新队列，会自动创建
        $FxLoginQueueName = "";
        $IyunLoginJobQueueName = "";
        // 3.当前任务所需业务数据，不能为resource类型，其他类型最终将转化为json形式的字符串
        $jobData = ['ts' => time(),'user_id'=>$user_info["id"], 'mobile' =>$mobile , 'name' => $wechat_user->nickname,'password'=>$password];
        // 4.将该任务推送到消息列表，等待对应的消费者去执行
        // 入队列，later延迟执行，单位秒，push立即执行
        Queue::later(10, $FxLoginJobClassName, $jobData, $FxLoginQueueName);
        Queue::later(10, $IyunLoginJobClassName, $jobData, $IyunLoginJobQueueName);
         $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注销登录.
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息.
     *
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->request('username');
        $nickname = $this->request->request('nickname');
        $bio = $this->request->request('bio');
        $avatar = $this->request->request('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        $user->nickname = $nickname;
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱.
     *
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->request('captcha');
        if (! $email || ! $captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (! Validate::is($email, 'email')) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (! $result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号.
     *
     * @param string $mobile   手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (! $mobile || ! $captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (! Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (! $result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }
    /**
     * 个人信息修改
     *
     * @return void
     */
    public function changebankcark(){
        $user = $this->auth->getUser();
        $username = $this->request->request('username');
        $bank_card = $this->request->request('bank_card');
        $sub_branch = $this->request->request('sub_branch');
        if (!$user) {
            $this->error(__('You are not logged in'));
        }
        if (! $bank_card || ! $sub_branch||!$username) {
            $this->error(__('Invalid parameters'));
        }
        $bank_map = ["CDB"=>"国家开发银行","ICBC"=>"中国工商银行","ABC"=>"中国农业银行","BOC"=>"中国银行","CCB"=>"中国建设银行","PSBC"=>"中国邮政储蓄银行","COMM"=>"交通银行","CMB"=>"招商银行","SPDB"=>"上海浦东发展银行","CIB"=>"兴业银行","HXBANK"=>"华夏银行","GDB"=>"广东发展银行","CMBC"=>"中国民生银行","CITIC"=>"中信银行","CEB"=>"中国光大银行","EGBANK"=>"恒丰银行","CZBANK"=>"浙商银行","BOHAIB"=>"渤海银行","SPABANK"=>"平安银行","SHRCB"=>"上海农村商业银行","YXCCB"=>"玉溪市商业银行","YDRCB"=>"尧都农商行","BJBANK"=>"北京银行","SHBANK"=>"上海银行","JSBANK"=>"江苏银行","HZCB"=>"杭州银行","NJCB"=>"南京银行","NBBANK"=>"宁波银行","HSBANK"=>"徽商银行","CSCB"=>"长沙银行","CDCB"=>"成都银行","CQBANK"=>"重庆银行","DLB"=>"大连银行","NCB"=>"南昌银行","FJHXBC"=>"福建海峡银行","HKB"=>"汉口银行","WZCB"=>"温州银行","QDCCB"=>"青岛银行","TZCB"=>"台州银行","JXBANK"=>"嘉兴银行","CSRCB"=>"常熟农村商业银行","NHB"=>"南海农村信用联社","CZRCB"=>"常州农村信用联社","H3CB"=>"内蒙古银行","SXCB"=>"绍兴银行","SDEB"=>"顺德农商银行","WJRCB"=>"吴江农商银行","ZBCB"=>"齐商银行","GYCB"=>"贵阳市商业银行","ZYCBANK"=>"遵义市商业银行","HZCCB"=>"湖州市商业银行","DAQINGB"=>"龙江银行","JINCHB"=>"晋城银行JCBANK","ZJTLCB"=>"浙江泰隆商业银行","GDRCC"=>"广东省农村信用社联合社","DRCBCL"=>"东莞农村商业银行","MTBANK"=>"浙江民泰商业银行","GCB"=>"广州银行","LYCB"=>"辽阳市商业银行","JSRCU"=>"江苏省农村信用联合社","LANGFB"=>"廊坊银行","CZCB"=>"浙江稠州商业银行","DYCB"=>"德阳商业银行","JZBANK"=>"晋中市商业银行","BOSZ"=>"苏州银行","GLBANK"=>"桂林银行","URMQCCB"=>"乌鲁木齐市商业银行","CDRCB"=>"成都农商银行","ZRCBANK"=>"张家港农村商业银行","BOD"=>"东莞银行","LSBANK"=>"莱商银行","BJRCB"=>"北京农村商业银行","TRCB"=>"天津农商银行","SRBANK"=>"上饶银行","FDB"=>"富滇银行","CRCBANK"=>"重庆农村商业银行","ASCB"=>"鞍山银行","NXBANK"=>"宁夏银行","BHB"=>"河北银行","HRXJB"=>"华融湘江银行","ZGCCB"=>"自贡市商业银行","YNRCC"=>"云南省农村信用社","JLBANK"=>"吉林银行","DYCCB"=>"东营市商业银行","KLB"=>"昆仑银行","ORBANK"=>"鄂尔多斯银行","XTB"=>"邢台银行","JSB"=>"晋商银行","TCCB"=>"天津银行","BOYK"=>"营口银行","JLRCU"=>"吉林农信","SDRCU"=>"山东农信","XABANK"=>"西安银行","HBRCU"=>"河北省农村信用社","NXRCU"=>"宁夏黄河农村商业银行","GZRCU"=>"贵州省农村信用社","FXCB"=>"阜新银行","HBHSBANK"=>"湖北银行黄石分行","ZJNX"=>"浙江省农村信用社联合社","XXBANK"=>"新乡银行","HBYCBANK"=>"湖北银行宜昌分行","LSCCB"=>"乐山市商业银行","TCRCB"=>"江苏太仓农村商业银行","BZMD"=>"驻马店银行","GZB"=>"赣州银行","WRCB"=>"无锡农村商业银行","BGB"=>"广西北部湾银行","GRCB"=>"广州农商银行","JRCB"=>"江苏江阴农村商业银行","BOP"=>"平顶山银行","TACCB"=>"泰安市商业银行","CGNB"=>"南充市商业银行","CCQTGB"=>"重庆三峡银行","XLBANK"=>"中山小榄村镇银行","HDBANK"=>"邯郸银行","KORLABANK"=>"库尔勒市商业银行","BOJZ"=>"锦州银行","QLBANK"=>"齐鲁银行","BOQH"=>"青海银行","YQCCB"=>"阳泉银行","SJBANK"=>"盛京银行","FSCB"=>"抚顺银行","ZZBANK"=>"郑州银行","SRCB"=>"深圳农村商业银行","BANKWF"=>"潍坊银行","JJBANK"=>"九江银行","JXRCU"=>"江西省农村信用","HNRCU"=>"河南省农村信用","GSRCU"=>"甘肃省农村信用","SCRCU"=>"四川省农村信用","GXRCU"=>"广西省农村信用","SXRCCU"=>"陕西信合","WHRCB"=>"武汉农村商业银行","YBCCB"=>"宜宾市商业银行","KSRB"=>"昆山农村商业银行","SZSBK"=>"石嘴山银行","HSBK"=>"衡水银行","XYBANK"=>"信阳银行","NBYZ"=>"鄞州银行","ZJKCCB"=>"张家口市商业银行","XCYH"=>"许昌银行","JNBANK"=>"济宁银行","CBKF"=>"开封市商业银行","WHCCB"=>"威海市商业银行","HBC"=>"湖北银行","BOCD"=>"承德银行","BODD"=>"丹东银行","JHBANK"=>"金华银行","BOCY"=>"朝阳银行","LSBC"=>"临商银行","BSB"=>"包商银行","LZYH"=>"兰州银行","BOZK"=>"周口银行","DZBANK"=>"德州银行","SCCB"=>"三门峡银行","AYCB"=>"安阳银行","ARCU"=>"安徽省农村信用社","HURCB"=>"湖北省农村信用社","HNRCC"=>"湖南省农村信用社","NYNB"=>"广东南粤银行","LYBANK"=>"洛阳银行","NHQS"=>"农信银清算中心","CBBQS"=>"城市商业银行资金清算中心"];
        $data=[
            'cardNo'=>$bank_card ,
            'cardBinCheck'=>'true'
        ];
        $http=Http::get("https://ccdcapi.alipay.com/validateAndCacheCardInfo.json",$data,['Content-type: application/json']);
        $data = json_decode($http,true);
   
        if($data['validated']==false){
            $this->error(__('Bankcard in failed'));
        }
        // else{
        //     $bank_short=$data['bank'];
        //     $bank_name=$bank_map[$data['bank']];
        // }
        $verification = $user->verification;
        $verification->username = 1;
        $user->verification = $verification;
        $user->username = $username;
        $user->bank_card = $bank_card;
        $user->sub_branch = $sub_branch;
        $user->save();
        $this->success('修改成功',$user);
    }
    /**
     * 第三方登录.
     *
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->request('platform');
        $code = $this->request->request('code');
        $config = get_addon_config('third');
        if (! $config || ! isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result,
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->request('type');
        $mobile = $this->request->request('mobile');
        $email = $this->request->request('email');
        $newpassword = $this->request->request('newpassword');
        $captcha = $this->request->request('captcha');
        if (! $newpassword || ! $captcha) {
            $this->error(__('Invalid parameters'));
        }
        if ($type == 'mobile') {
            if (! Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::where('mobile',$mobile)->find();
            if (! $user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (! $ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (! Validate::is($email, 'email')) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::where('email',$email)->find();
            if (! $user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (! $ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }
}
